﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.Configuration;
using System.Web;
using System.IO;
using System.Collections;

namespace Core
{
    public static partial class contest
    {
        public static dynamic showRanklist(int cid)
        {
            var sql = new Sql.SqlDataContext();
            if (sql.Contest.Where(row => row.cid == cid).FirstOrDefault() == null)
                return new
                {
                    msg = "比赛不存在",
                    success = false
                };
            var ply = from g in sql.Ranklist
                      where g.cid == cid
                      orderby g.ac descending, g.usetime
                      select g;
            var ps = sql.ContestProblem.Where(row => row.cid == cid);
            var result = new Hashtable[ply.Count()];
            int i = 0;
            foreach (var p in ply)
            {
                result[i] = new Hashtable
                {
                    {"rank", i == 0 ? i + 1 : (((int)result[i - 1]["ac"] == p.ac
                                              && (int)result[i - 1]["usetime"] == p.usetime) ? (int)result[i - 1]["rank"] : i + 1)},
                    {"username", p.username},
                    {"usetime", p.usetime},
                    {"ac",p.ac},
                    {"submit",p.submit}
                };
                foreach (var g in ps)
                {
                    result[i].Add(g.ps.ToString(), g.ps);
                    var pts = sql.ContestSolve.FirstOrDefault(row => row.cid == cid &&
                                                         row.ps == g.ps && row.username == p.username);
                    if (pts == null)
                    {
                        result[i].Add(g.ps + "_ac", 0);
                        result[i].Add(g.ps + "_submit", 0);
                    }
                    else
                    {
                        result[i].Add(g.ps + "_ac", pts.ac);
                        result[i].Add(g.ps + "_submit", pts.submit);
                    }
                }
                ++i;
            }
            var total = result.Count();
            return new
            {
                result,
                total,
                success = true
            };
        }
    }
}
